package server.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import commons.Manager;
import commons.User;
import commons.exceptions.ProcessException;
import server.filters.RestrictedPagesToConnectedUser;
import server.forms.ConnectionForm;
import server.utilities.CookieManager;

/**
 * Servlet used to authenticate an user
 * @author Romain Pellerin
 */
public class Connection extends HttpServlet {

	private static final long serialVersionUID = -2270199258439695915L;
	public static final String SESSION_USER = "user";
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (RestrictedPagesToConnectedUser.getUserIfConnected(request) != null)
			response.sendRedirect("console");
		else {
			request.setAttribute("nickname", CookieManager.getSavedCookie(request, "nickname"));
			this.getServletContext().getRequestDispatcher("/WEB-INF/jsp_pages/connection.jsp").forward(request, response);
		}
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		HttpSession session = request.getSession();
		ConnectionForm form = new ConnectionForm();
		form.connectUser(request);
		request.setAttribute("nickname", form.getNickname());
		
		if (form.getError()==null) { // no error
			User user = form.getUser();
			session.setAttribute(SESSION_USER, user);
			CookieManager.saveNickname(user.getName(), response);
			try {
				Manager.getInstance().addUser(user);
				response.sendRedirect("console");
				return;
			} catch (ProcessException e) {
				request.setAttribute("message_error", e.getMessage());
			}
		}
		else {
			request.setAttribute("message_error", form.getError());
		}
		session.setAttribute(SESSION_USER, null);
		this.getServletContext().getRequestDispatcher("/WEB-INF/jsp_pages/connection.jsp").forward(request, response);
	}	
}
